import { defineStore } from "pinia";//引入pinia
 
export const useGoodCarStore = defineStore("goodCar", {
  id: "demo",//缓存的key
  state: () => ({ count: 0, listArr: [], selectListArr: [] }),
  getters: {
    double: (state) => state.count * 2,
    // 购物车中的总数量
    totalNum: (state) => {
      let num = 0;
      if (state.selectListArr.length > 0) {
        num = state.selectListArr.reduce((acc, cur) => {
          return acc + cur.num;
        }, 0);
      }
      return num;
    },
    // 购物车中的总价格
    totalPrice: (state) => {
      let price = 0;
      if (state.selectListArr.length > 0) {
        price = state.selectListArr.reduce((acc, cur) => {
          return acc + cur.num * cur.price;
        }, 0);
      }
      return price;
    },
  },
  actions: {
    increment(state) {
      if (this.listArr.length == 0) {
        this.listArr.push({
          ...state,
          num: 1,
        });
      } else {
        let index = this.listArr.findIndex((item) => item.id == state.id);
        if (index != -1) {
          this.listArr[index].num = this.listArr[index].num + 1;
        } else {
          this.listArr.push({
            ...state,
            num: 1,
          });
        }
      }
      console.log("商品数组：", this.listArr);
    },
    // 选中购物车中的商品
    selectGoodCar(state) {
      this.selectListArr = state;
    },
  },
  // 开启数据持久化
  persist: true,
});